from django.db import transaction
from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response

from api.conf import order_status
from api.serializers.order_serializer import OrderUpdateStatusSerializer, \
    OrderListRequestSerializer, OrderListResponseSerializer
from api.utils.paginator import get_page
from app.models import Order
from app.models.fm_user import USER_TYPE_SALES


@api_view(['GET'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def get_order_list(request: Request, order_status='0'):
    user = request.user
    if user.user_type != USER_TYPE_SALES:
        raise ValidationError(detail=u'当前用户不是销售')
    # serializer = OrderListRequestSerializer(data=request.data)
    # request_page = 1
    # if serializer.is_valid():
    #     request_page = serializer.validated_data['page']
    order_status = [int(status) for status in order_status.split(',')]
    if 0 in order_status:
        orders = Order.objects.filter(user__sales=user).order_by("-created_datetime")
    else:
        orders = Order.objects.filter(user__sales=user, status__in=order_status).order_by("-created_datetime")
    # orders, has_more = get_page(orders, request_page)
    response_data = OrderListResponseSerializer({'orders': orders, 'has_more': False}).data
    return Response(response_data)


@api_view(['PUT'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
@transaction.atomic()
def confirm_order(request: Request):
    serializer = OrderUpdateStatusSerializer(data=request.data)
    if serializer.is_valid():
        order = serializer.validated_data['order_id']
        if request.user != order.user.sales or order.status != order_status.REQUEST_RETURN_DEPOSIT:
            raise ValidationError(detail=u'订单状态不正确')
        try:
            order = Order.objects.select_for_update().get(id=order.id,
                                                          user__sales=request.user,
                                                          status=order_status.REQUEST_RETURN_DEPOSIT)
        except Order.DoesNotExist:
            raise ValidationError(detail=u'订单不存在')
        order.status = order_status.FINISHED  # 完成
        order.save()
        return Response({'detail': u'订单完成'})
    else:
        raise ValidationError(serializer.errors)


@api_view(['PUT'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
@transaction.atomic()
def shipped_order(request: Request):
    serializer = OrderUpdateStatusSerializer(data=request.data)
    if serializer.is_valid():
        order = serializer.validated_data['order_id']
        if request.user != order.user.sales or order.status != order_status.NOT_SHIPPED:
            raise ValidationError(detail=u'订单状态不正确')
        try:
            order = Order.objects.select_for_update().get(id=order.id,
                                                          user__sales=request.user,
                                                          status=order_status.NOT_SHIPPED)
        except Order.DoesNotExist:
            raise ValidationError(detail=u'订单不存在')
        order.status = order_status.TO_BE_RECEIVED  # 待收货
        order.save()
        return Response({'detail': u'订单完成'})
    else:
        raise ValidationError(serializer.errors)
